﻿using Hd.AbpCoding.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Dynamic.Core;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;

namespace Hd.AbpCoding.Projects
{
    public class ProjectEfCoreRepository : EfCoreRepository<AbpCodingDbContext, Project, Guid>, IProjectRepository
    {
        public ProjectEfCoreRepository(IDbContextProvider<AbpCodingDbContext> dbContextProvider) : base(dbContextProvider)
        {
        }

        public async Task<Project> FindByNameAsync(string name, CancellationToken cancellationToken = default)
        {
            return await this.Where(x => x.Name == name)
                .FirstOrDefaultAsync(GetCancellationToken(cancellationToken));
        }

        public async Task<int> GetCountAsync(string filter, CancellationToken cancellationToken = default)
        {
            return await this.WhereIf(!filter.IsNullOrEmpty(), x => x.Name.Contains(filter) ||
            (!string.IsNullOrEmpty(x.Description) && x.Description.Contains(filter)) ||
            (!string.IsNullOrEmpty(x.RootNamespace) && x.RootNamespace.Contains(filter)))
                 .CountAsync(GetCancellationToken(cancellationToken));

        }

        public async Task<List<Project>> GetListAsync(string filter, int skipCount = 0, int maxResultCount = int.MaxValue, string sorting = null, bool includeDetails = false, CancellationToken cancellationToken = default)
        {
            return await this.WhereIf(!filter.IsNullOrEmpty(), x => x.Name.Contains(filter) ||
            (!string.IsNullOrEmpty(x.Description) && x.Description.Contains(filter)) ||
            (!string.IsNullOrEmpty(x.RootNamespace) && x.RootNamespace.Contains(filter)))
                .OrderBy(sorting ?? nameof(Project.CreationTime))
                .PageBy(skipCount, maxResultCount)
                .ToListAsync(GetCancellationToken(cancellationToken));
        }
    }
}
